Joining an Available Network Session
Finally, implement the JoinSession method, which joins one of the available network sessions, registesr for session events, and sets the next GameState. Add the following method to your game:
// Creates a session using a AvailableNetworkSession index
private void JoinSession(int sessionID)
{
// Join an existing NetworkSession
try
{
networkSession = NetworkSession.Join(availableSessions[sessionID]);
}
catch (NetworkSessionJoinException ex)
{
gameMessages.Add(new DisplayMessage("Faild to connect to session: " +
ex.JoinError.ToString(),
TimeSpan.FromSeconds(2)));
// Check for sessons again
FindSession();
}
// Register for NetworkSession events
networkSession.GameStarted +=
new EventHandler<GameStartedEventArgs>(networkSession_GameStarted);
networkSession.GameEnded +=
new EventHandler<GameEndedEventArgs>(networkSession_GameEnded);
networkSession.GamerJoined +=
new EventHandler<GamerJoinedEventArgs>(networkSession_GamerJoined);
networkSession.GamerLeft +=
new EventHandler<GamerLeftEventArgs>(networkSession_GamerLeft);
networkSession.SessionEnded +=
new EventHandler<NetworkSessionEndedEventArgs>(networkSessionSessionEnded);
// Set the correct GameState. The NetworkSession may have already started a game.
if (networkSession.SessionState == NetworkSessionState.Playing)
gameState = GameState.PlayingGame;
else
gameState = GameState.GameLobby;
}
The JoinSession method that you added to your game takes the index value into the availableSessions collection to use when joining the session. The NetworkSession.Join method takes a single argument, which is the AvailableNetworkSession to join. Join can throw a NetworkSessionJoinException
if for some reason the session is not joinable anymore—for example, if
the session becomes full between searching for available sessions and
trying to join the session. If you receive the exception, you search
again and print an error message.
After joining the session, you have a valid NetworkSession similar to when you created the session, so register for all of the same events. Finally, set the current gameState depending on whether the session you are joining is already playing the game or is in the lobby.
Note
As with the NetworkSession.Create and NetworkSession.Find methods, NetworkSession.Join also has an asynchronous version BeginJoin and EndJoin.
Running the sample now
should enable you to create a session on one machine and join that
session from another. The lobby should look similar to Figure 10.
Both players can set their ready state, which should update on both machines. If the host presses the Start button, the game begins. In the game playing state, both players can move their name around the screen (see Figure 11).
If the host presses the Back button, the game ends and all players move back into the lobby. If the host presses the Back button again, the session ends and all players return to the main menu (see Figure 12).
Sending Player Invites
Xbox
LIVE enables you to connect with players from around the world. While
playing a game, you might want to invite your friends to join you. You
might also receive invitations from others to join their game. Adding
support for game invites is tremendously easy with XNA Game Studio.
In the GameLobbyUpdate method, add the following code:
// Invite other players
if (ButtonPressed(Buttons.X) && !Guide.IsVisible)
Guide.ShowGameInvite(PlayerIndex.One, null);
Guide.ShowGameInvite shows a list of the player’s friends to invite to the current game.
Now, you need to register for the NetworkSession.InviteAccepted event, which fires after a player accepts the invite.
// Register for the invite event
NetworkSession.InviteAccepted +=
new EventHandler<InviteAcceptedEventArgs>(NetworkSessionInviteAccepted);
Finally, implement the NetworkSession_InviteAccepted method.
void NetworkSession_InviteAccepted(object sender, InviteAcceptedEventArgs e)
{
if (networkSession != null && !networkSession.IsDisposed)
networkSession.Dispose();
if (!e.IsCurrentSession)
networkSession = NetworkSession.JoinInvited(1);
}
First, NetworkSession_InviteAccepted disposes of any NetworkSession that might be active. Then, check to make sure you are not already in the session before you call the NetworkSession.JoinInvited method. This method takes the number of local gamers that are joining. Now, your game is ready for game invites.
Note
If the account you are using is not an Xbox LIVE account, then the Guide.ShowGameInvite method throws an exception because local players can’t send invites.
Party Invites
A party allows for up to eight
players to group together no matter which game they are playing. The
players in the party can chat with each other even while playing
different games. This is great if you want to chat with a friend while
you play separate games.
While you are playing a game,
you can view available network sessions of your party members that you
can join. To display the list of sessions you can join, add the
following to the MainMenuUpdate method:
// Show a party sessions the player can join
if (ButtonPressed(Buttons.Y) && !Guide.IsVisible)
Guide.ShowPartySessions(PlayerIndex.One);
You can also invite the
players in your party to your game session. To show the party screen
from your game, add the following to the GameLobbyUpdate method:
// Show the party screen
if (ButtonPressed(Buttons.Y) && !Guide.IsVisible)
Guide.ShowParty(PlayerIndex.One);
Simulating Real World Network Conditions
As expected, the conditions
and speed that the network traffic performs in your game is slower than
what you are currently seeing. Your connection from your PC to your
Xbox 360 over your local area network is close to perfect. The physical
distance is low and the amount of other traffic your packets have to
deal with is relatively low. Out in the wild, Internet conditions can
vary greatly. Your connection to another machine has a higher latency
and you can experience packet loss.
Developers have a
difficult time handling these conditions unless they could simulate them
within their development environment. NetworkSession provides two properties that enable the developer to simulate real-world network conditions.
The NetworkSession.SimulatedLatency property is a TimeSpan,
which is a simulated latency between the machines in the session. Games
running on Xbox LIVE games are expected to handle latencies of 200
milliseconds while still enabling the game to be playable.
The NetworkSession.SimulatedPacketLoss property is a float
value in the rage of 0 for no packet loss to 1 for 100 percent packet
loss. Xbox LIVE games are expected to handle packet loss around 10
percent or a value of 0.1f.